<route lang="json5" type="page">
{
	style: {
		navigationStyle: 'default',
		navigationBarBackgroundColor: '#FCFCFC',
		navigationBarTextStyle: 'black',
		backgroundColor: '#FCFCFC',
		navigationBarTitleText: '发布共读计划',
	},
}
</route>
<template>
	<view class="page-bookrack">
		<view
			class="w-full flex flex-col box-border pb-[168rpx]"
			style="height: calc(100% - 168rpx); overflow-y: scroll; background-color: #fcfcfc"
			:style="{ height: contentHeight + 'rpx' }"
		>
			<view class="flex items-center mt-[30rpx]">
				<text class="text-[43rpx] text-[#303030] ml-[48rpx] font-bold">设置共读计划</text>
				<text class="text-[44rpx] text-[#2BA5E0] ml-[15rpx] font-bold">3</text>
				<text class="text-[37rpx] text-[#2BA5E0] font-bold">/3</text>
			</view>

			<uni-forms ref="formRef" :rules="rules" :modelValue="formData">
				<view class="page-personal px-4 box-border pb-4">
					<text class="flex text-[43rpx] text-[#303030] ml-[20rpx] mt-[60rpx] font-bold">名称</text>
					<view class="w-full box-border mb-3 mt-4">
						<view
							class="px-[32rpx] rounded-[20rpx] px-4 py-[20rpx]"
							style="background-color: #f6f7f9"
						>
							<uni-forms-item name="title">
								<view class="w-full flex h-full justify-between items-center box-border">
									<input
										class="flex-1"
										placeholder="请为共读计划命名"
										v-model="formData.title"
										@input="setValue('title', formData.title)"
									/>
								</view>
							</uni-forms-item>
						</view>
					</view>
					<text class="flex text-[43rpx] text-[#303030] ml-[20rpx] mt-[30rpx] font-bold"
						>持续时间</text
					>
					<view class="w-full box-border mb-3 mt-4">
						<view
							class="px-[32rpx] rounded-[20rpx] px-4 py-[20rpx]"
							style="background-color: #f6f7f9"
						>
							<uni-forms-item name="start_time" label="开始时间">
								<view class="w-full flex h-full justify-between items-center box-border">
									<view
										class="flex-1"
										:style="{ color: formData.start_time ? '#303030' : '#ABABAB' }"
										@tap="openData(false)"
										>{{ formData.start_time || '请选择' }}</view
									>
									<image
										class="w-[22rpx] h-[16rpx]"
										:src="baseImg + '/beiyueshumu_xxjt.png'"
									></image>
								</view>
							</uni-forms-item>
						</view>
					</view>
					<view class="w-full box-border mb-3 mt-4">
						<view
							class="px-[32rpx] rounded-[20rpx] px-4 py-[20rpx]"
							style="background-color: #f6f7f9"
						>
							<uni-forms-item name="duration" label="持续时间">
								<view
									class="w-full flex h-full justify-between items-center box-border"
									@tap="openModal('duration', '选择持续时间')"
								>
									<view
										class="flex-1"
										:style="{ color: formData.durationName ? '#2BA5E0' : '#ABABAB' }"
										>{{ formData.durationName || '请选择' }}</view
									>
									<image
										class="w-[22rpx] h-[16rpx]"
										:src="baseImg + '/beiyueshumu_xxjt.png'"
									></image>
								</view>
							</uni-forms-item>
						</view>
					</view>
					<view class="w-full box-border mb-3 mt-4">
						<view
							class="px-[32rpx] rounded-[20rpx] px-4 py-[20rpx]"
							style="background-color: #f6f7f9"
						>
							<uni-forms-item name="end_time" label="截止时间">
								<view
									class="w-full flex h-full justify-between items-center box-border"
									v-if="formData.duration != '8'"
								>
									<input
										class="flex-1"
										placeholder=""
										:disabled="true"
										style="color: #ababab"
										v-model="formData.end_time"
									/>
								</view>
								<view class="w-full flex h-full justify-between items-center box-border" v-else>
									<view
										class="flex-1"
										:style="{ color: formData.end_time ? '#303030' : '#ABABAB' }"
										@tap="openData(true)"
										>{{ formData.end_time || '请选择' }}</view
									>
									<image
										class="w-[22rpx] h-[16rpx]"
										:src="baseImg + '/beiyueshumu_xxjt.png'"
									></image>
								</view>
							</uni-forms-item>
						</view>
					</view>
				</view>
			</uni-forms>
			<uv-datetime-picker
				ref="datetimePicker"
				v-model="timeData"
				mode="date"
				@confirm="confirmPicker"
			>
			</uv-datetime-picker>
			<uni-popup ref="popup" :mask-click="false" type="bottom" background-color="transparent">
				<view class="w-full h-[824rpx] px-6 py-4 box-border">
					<view
						class="w-full bg-white h-full rounded-[30rpx] py-6 box-border flex flex-col justify-center"
					>
						<view class="w-full h-[53rpx] flex justify-between items-center px-6 box-border">
							<image
								@tap="closeModal"
								:src="baseImg + '/close-btn.png'"
								class="w-[44rpx] h-[44rpx]"
							></image>
							<text class="text-[#303030] text-[44rpx]">{{ modalInfo.title }}</text>
							<view
								class="text-[#fff] text-[29rpx] rounded-[29rpx] h-[53rpx] flex px-4 justify-center items-center"
								style="background: #2ba5e0"
								@tap="confirm"
								>确认</view
							>
						</view>
						<view class="w-full pt-6 box-border" style="height: calc(100% - 53rpx)">
							<view class="h-full flex justify-between py-2 box-border">
								<scroll-view scroll-y class="w-full h-full">
									<view
										v-for="item in modalList"
										:key="item.id"
										@tap="setItem(item.id, item.name)"
										class="w-full flex justify-center items-center mb-2 last:mb-0"
									>
										<view
											class="max-w-full px-[38rpx] h-[54rpx] box-border flex justify-center items-center rounded-[27rpx] text-[#303030] text-[29rpx]"
											:style="{
												background: modalInfo.id === item.id ? '#44C651' : '',
												color: modalInfo.id === item.id ? '#fff' : '#303030',
											}"
											><text class="truncate">{{ item.name }}</text></view
										>
									</view>
								</scroll-view>
							</view>
						</view>
					</view>
				</view>
			</uni-popup>
		</view>
		<view index="2" class="container-6">
			<view index="1" src="" class="title-wrapper" style="background-color: #ffd032" @tap="goBack">
				<text index="0" class="title-9">上一步</text>
			</view>
			<!-- 不可点击 -->
			<view index="1" src="" class="title-wrapper" style="display: none; background-color: #cbd7e5">
				<text index="0" class="title-9" style="color: #f4f7f4">确认发布</text>
			</view>
			<!-- 可点击 -->
			<view index="1" src="" class="title-wrapper" style="background-color: #2ba5e0" @tap="submit">
				<text index="0" class="title-9" style="color: #f4f7f4">确认发布</text>
			</view>
		</view>
	</view>
</template>

<script lang="ts" setup>
import { addPlanApi } from '@/service/plan';
import { addTeacherInfo } from '@/service/user';
import { usePlanStore } from '@/store';
import { systemInfo } from '@/utils/getSystemInfo';
import dayjs from 'dayjs';
import { storeToRefs } from 'pinia';
const { contentHeight } = systemInfo();

const baseImg = ref(import.meta.env.VITE_STATIC_IMAGE);
const planStore = usePlanStore();
const { planInfo } = storeToRefs(planStore);
const formRef = ref(null);
const popup = ref(null);
const title = ref('');
const start_time = ref('');
const end_time = ref('');
const duration = ref('');
const modalList = ref([]);
const modalInfo = ref({
	type: '',
	title: '',
	id: null,
	name: '',
});
const datetimePicker = ref(null);
const timeData = ref(Number(new Date()));
const isEndtimeChoose = ref(false); //ture为开始时间选择，false为结束时间选择
const openData = (isEnd: boolean) => {
	isEndtimeChoose.value = isEnd;

	datetimePicker.value.open();
};
const confirmPicker = (e: any) => {
	console.log(e);
	//formData.value.start_time = dayjs(e.value).format('YYYY-MM-DD');
	if ((formData.value.duration && formData.value.duration !== '8') || !formData.value.duration) {
		formData.value.start_time = dayjs(e.value).format('YYYY-MM-DD');
		if (!formData.value.duration) return;
		getEndTime(formData.value.start_time, formData.value.duration);
	} else {
		// 检查date1是否在date2之前
		// console.log(date1.isBefore(date2)); // 输出: true
		if (dayjs(formData.value.start_time).isBefore(dayjs(e.value))) {
			formData.value.end_time = dayjs(e.value).format('YYYY-MM-DD');
		} else {
			uni.showToast({
				icon: 'none',
				title: '结束日期不能小于开始日期',
			});
			formData.value.end_time = '';
		}
	}
};
const formData = ref({
	title: '',
	start_time: '',
	end_time: '',
	duration: '',
	durationName: '',
});
const rules = ref({
	title: {
		rules: [
			{
				required: true,
				errorMessage: '标题不能为空',
			},
		],
	},
	start_time: {
		rules: [
			{
				required: true,
				errorMessage: '开始时间不能为空',
			},
		],
	},
	duration: {
		rules: [
			{
				required: true,
				errorMessage: '持续时间不能为空',
			},
		],
	},
});

const setValue = (name, value) => {
	formRef.value?.setValue(name, value);
};

const openModal = (type?, title?) => {
	modalInfo.value.type = type;
	modalInfo.value.title = title;
	let id = '';
	let name = '';
	let list = [];
	if (type === 'duration') {
		list = [
			{ id: '1', name: '无限期' },
			{ id: '2', name: '7天' },
			{ id: '3', name: '8天' },
			{ id: '4', name: '9天' },
			{ id: '5', name: '15天' },
			{ id: '6', name: '30天' },
			{ id: '7', name: '60天' },
			{ id: '8', name: '自定义' },
		];
		id = formData.value.duration;
		name = formData.value.durationName;
	}
	modalList.value = list;
	modalInfo.value.id = id;
	modalInfo.value.name = name;
	popup.value?.open();
};

const closeModal = () => {
	modalInfo.value = {
		type: '',
		title: '',
		id: '',
		name: '',
	};
	popup.value?.close();
};

const getAddDate = (oldDate, daysToAdd) => {
	// 假设我们有一个日期字符串
	var dateString = oldDate;

	// 将字符串转换成Date对象
	var initialDate = new Date(dateString);

	if (daysToAdd == '') return '无限期';

	// 检查字符串是否成功转换（不是所有格式的日期字符串都能被所有浏览器正确解析）
	if (isNaN(initialDate.getTime())) {
		console.error('Invalid date string');
	} else {
		// 同样的，增加天数
		initialDate.setDate(initialDate.getDate() + daysToAdd);

		//console.log(initialDate.toDateString());
		return initialDate.toDateString();
	}
};
const getEndTime = (start_time, duration) => {
	let daysToAdd: string | number = '';
	if (duration === '1') {
		formData.value.end_time = '无限期';
		return;
	}
	if (duration === '8') {
		formData.value.end_time = '';
		return;
	}

	switch (duration) {
		case '1':
			daysToAdd = '无限期';
		case '2':
			daysToAdd = 7;
			break;
		case '3':
			daysToAdd = 8;
			break;
		case '4':
			daysToAdd = 9;
			break;
		case '5':
			daysToAdd = 15;
			break;
		case '6':
			daysToAdd = 30;
			break;
		case '7':
			daysToAdd = 60;
			break;
		case '8':
			daysToAdd = '-1';
			break;
		default:
			daysToAdd = 0;
			break;
	}
	formData.value.end_time = dayjs(getAddDate(start_time, daysToAdd)).format('YYYY-MM-DD');
};
const confirm = () => {
	const { type } = modalInfo.value;
	if (!modalInfo.value.id) {
		uni.showToast({
			icon: 'none',
			title: modalInfo.value.title,
		});
		return;
	}
	formData.value[type] = modalInfo.value.id;

	if (type === 'duration') {
		formData.value.durationName = modalInfo.value.name;
		if (formData.value.start_time) {
			//开始时间选定
			getEndTime(formData.value.start_time, formData.value.duration);
		}
	}
	closeModal();
};

const setItem = (id, name) => {
	modalInfo.value.id = id;
	modalInfo.value.name = name;
};

const submit = () => {
	uni.showLoading({ title: '保存中...' });
	if (!formData.value.start_time) {
		uni.showToast({
			icon: 'none',
			title: '请先选择开始时间',
		});
		return;
	}
	if (!formData.value.duration) {
		uni.showToast({
			icon: 'none',
			title: '请先选择持续时间',
		});
		return;
	}
	if (!formData.value.end_time) {
		uni.showToast({
			icon: 'none',
			title: '请先选择结束时间',
		});
		return;
	}
	formRef.value
		?.validate()
		.then(async res => {
			try {
				const data = await addPlanApi({
					...res,
					end_time: formData.value.end_time == '无限期' ? '' : formData.value.end_time,
					class_id: planInfo.value.class_id,
					book_ids: planInfo.value.book_ids.map(num => num.toString()),
				});
				uni.hideLoading();
				if (data.status_code === 200) {
					uni.showToast({
						icon: 'none',
						title: '保存成功',
					});
					planStore.clearPlanInfo();
					uni.navigateTo({
						url: '/pages/pages-readingPlan/readingPlan/index',
					});
				} else {
					uni.showToast({
						icon: 'none',
						title: data.message,
					});
				}
			} catch (error) {
				console.log('error===>', error);
				uni.showToast({
					icon: 'none',
					title: '保存失败,请重试',
				});
				uni.hideLoading();
			}
		})
		.catch(err => {
			uni.hideLoading();
		});
};
const goBack = () => {
	planStore.setPlanInfo({
		...planStore.planInfo,
		...{
			title: formData.value.title.trim(),
			start_time: formData.value.start_time,
			duration: formData.value.duration,
			duration_name: formData.value.durationName,
			end_time: formData.value.end_time,
		},
	});

	uni.navigateTo({
		url: '/pages/releasePlan/two/index',
	});
};
onShow(() => {
	formData.value.title = planInfo.value.title;
	formData.value.start_time = planInfo.value.start_time;
	formData.value.duration = planInfo.value.duration;
	formData.value.durationName = planInfo.value.duration_name;
	formData.value.end_time = planInfo.value.end_time;
});
</script>
<script lang="ts">
export default {
	options: { styleIsolation: 'shared' },
};
</script>

<style lang="scss">
.uni-forms-item {
	padding-bottom: 0 !important;
	margin-bottom: 0 !important;
}

.uni-forms-item__label {
	width: 170rpx !important;
	color: #303030 !important;
}
.no-label {
	width: auto !important;
}

page {
	background: #f6f6f6;
}
</style>
<style lang="scss" scoped>
.uni-forms-item {
	margin-bottom: 0 !important;
}

.page-bookrack {
	width: 100%;
	height: 100vh;
	background-color: #fcfcfc;
}

.releasePlanOne_boxMt {
	margin-top: 25rpx;
}

.releasePlanOne_boxMt:first-child {
	margin-top: 80rpx;
}

.releasePlanOne_box {
	display: block;
	padding: 35rpx 0 24rpx;
	background: #fff;
	border: #fff 4rpx solid;
	border-radius: 31rpx;
	box-shadow:
		0 0 4rpx 0 rgb(0 0 0 / 3%),
		0 7rpx 20rpx 0 rgb(0 0 0 / 7%);
}

.releasePlanOne_boxAhov {
	display: block;
	padding: 35rpx 0 24rpx;
	background: #fff;
	border: #33a3e2 4rpx solid;
	border-radius: 31rpx;
}

.staudenDetails_topLeftBox_image {
	float: left;
	width: 102rpx;
}

.staudenDetails_topLeftBox {
	float: left;
	width: calc(100% - 138rpx);
	min-height: 114rpx;

	.caption-7 {
		width: calc(100% - 22rpx);
		margin-top: 10rpx;
		margin-left: 22rpx;
		overflow: hidden;
		font-size: 36rpx;
		font-style: normal;
		line-height: 54rpx;
		color: rgb(48 48 48 / 100%);
		text-align: left;
		text-decoration: none;
		text-overflow: ellipsis;
		white-space: nowrap;
	}

	.staudenDetails_topRightBox_image {
		display: none;
		float: right;
		width: 60rpx;
		height: 60rpx;
		margin-top: 70rpx;
		margin-right: 30rpx;
	}

	.staudenDetails_topRightBox_imageAhov {
		display: block;
	}

	.title-6 {
		width: calc(100% - 105rpx);
		margin-left: 22rpx;
		overflow: hidden;
		text-align: left;
		text-decoration: none;
		text-overflow: ellipsis;
		white-space: nowrap;
	}

	.title-7 {
		float: left;
		height: 50rpx;
		padding: 0 20rpx;
		font-size: 25rpx;
		font-style: normal;
		line-height: 50rpx;
		color: #fff;
		background-color: #2ba5e0;
		border-radius: 10rpx;
	}

	.title-8 {
		float: left;
		font-size: 28rpx;
		font-style: normal;
		line-height: 50rpx;
		color: #909090;
	}
}

.releasePlanOne_bottomBox {
	display: block;
	float: left;
	width: calc(100% - 50rpx);
	margin: 28rpx 0 0 25rpx;

	.releasePlanOne_bottomBox_text {
		display: inline-block;
		height: 62rpx;
		padding: 0 28rpx;
		margin-right: 13rpx;
		font-size: 26rpx;
		line-height: 62rpx;
		color: #34a4e2;
		background-color: #f3f3f5;
		border-radius: 62rpx;
	}
}

.releasePlanOne_bottomBoxAhov {
	margin-top: 10rpx;
}

.container-6 {
	position: fixed;
	bottom: 0;
	left: 0;
	width: calc(100% - 120rpx);
	height: 166rpx;
	padding: 0 60rpx;
	background-color: #fcfcfc;

	.title-wrapper {
		float: left;
		width: 250rpx;
		height: 83rpx;
		margin: 40rpx 0 0 calc((100% - 500rpx) / 3);
		margin-top: 40rpx;
		overflow: hidden;
		font-size: 33rpx;
		line-height: 83rpx;
		color: #fff;
		text-align: center;
		text-overflow: ellipsis;
		white-space: nowrap;
		background-color: #2ba5e0;
		border-radius: 83rpx;
	}
}
</style>
